import requests
import json

# 登录获取auth_token
def zabbix_login(user, password, zabbix_url):
    """
    paras:
        user: 用户名
        password: 密码
        zabbix_url: zabbix Url
    """
    login_data = {
        'jsonrpc': '2.0',
        'method': 'user.login',
        'params': {
            'username': user,
            'password': password
        },
        'id': 1
    }

    zabbix_headers = {'Content-Type': 'application/json-rpc'}

    try:
        response = requests.post(zabbix_url, headers=zabbix_headers, data=json.dumps(login_data))
        response.raise_for_status()  # 如果不是2xx响应则会抛出HTTPError
        login_result = response.json()
        if 'result' in login_result:
            return login_result['result']
        else:
            print("登录失败:", login_result)
            # 处理登录失败的情况
    except requests.exceptions.RequestException as e:
        print("请求发生错误:", str(e))
        # 处理请求错误，如网络问题、服务器无响应等
    except json.JSONDecodeError:
        print("无法解析JSON响应")
        # 处理无法解析JSON的情况，如服务器返回的不是有效的JSON

def zabbix_logout(zabbix_url,tocken):
    logout_data = {
            "jsonrpc": "2.0",
            "method": "user.logout",
            "params": {
                "auth": tocken
            },
            "id": 2
        }
    
    zabbix_headers = {'Content-Type': 'application/json-rpc'}

    logout_response = requests.post(zabbix_url, headers=zabbix_headers, data=json.dumps(logout_data))
    if logout_response.status_code == 200:
        logout_result = logout_response.json()
        # print("登出成功")
    else:
        print("登出失败，状态码：", logout_response.status_code)

def zabbix_get_inventory(auth_tocken, zabbix_url):
    hosts_data = {
        'jsonrpc': '2.0',
        'method': 'host.get',
        'params': {
            "output": ['host', 'name', 'inventory'],
            'selectInventory': ['type', 'type_full', 'name', 'os', 'serialno_a', 'serialno_b', 'tag',
                                'hardware', 'software_app_a', 'software_app_b', 'software_app_c', 'software_app_d', 'software_app_e'],
            # 'groupids': '22',
        },
        'id': 2,
        'auth': auth_tocken
    }

    zabbix_headers = {'Content-Type': 'application/json-rpc'}

    vmserver = []
    physerver = []

    try:
        response = requests.post(zabbix_url, headers=zabbix_headers, data=json.dumps(hosts_data))
        host_result = response.json()
        host_zbx = host_result['result']

        for host in host_zbx:
            inventory = host['inventory']

            hostname = inventory['name']
            ipaddress = host['host']
            domain = inventory['tag']
            os_version = inventory['os']

            if inventory['os']:
                if 'Windows' in inventory['os']:
                    os_type = 'Windows'
                elif 'ESXi' in inventory['os']:
                    os_type = 'ESXi'
                else:
                    os_type = 'Linux'
            else:
                os_type = 'Others'

            manufacturer = inventory['type']
            model = inventory['type_full']
            sn = inventory['serialno_a']
            cpu_model = inventory['software_app_a']

            if inventory['software_app_b']:
                cpu_socket = inventory['software_app_b'].split()[0]
            else:
                cpu_socket = None

            if inventory['software_app_c']:
                cpu_cores = inventory['software_app_c'].split()[0]
            else:
                cpu_cores = None

            if inventory['software_app_d']:
                mem_size = inventory['software_app_d'].split()[0]
            else:
                mem_size = None

            if inventory['software_app_e']:
                mem_num = inventory['software_app_e'].split()[0]
            else:
                mem_num = None

            if inventory['hardware']:
                hardwares = inventory['hardware'].split()
                if 'KGB' == hardwares[1]:
                    disk_size = int(float(hardwares[0]) * 1000)
                elif 'GB' == hardwares[1]:
                    disk_size = round(float(hardwares[0]))
                else:
                    disk_size = None
            else:
                disk_size = None

            if sn: 
                physerver.append({
                    "hostname": hostname, "ipaddress": ipaddress, "domain": domain, "os_version": os_version, "os_type": os_type, "manufacturer": manufacturer,
                    "model": model, "sn": sn, "cpu_model": cpu_model, "cpu_socket": cpu_socket, "cpu_cores": cpu_cores, "mem_size": mem_size, "mem_num": mem_num,
                    "disk_size": disk_size,
                })
            else:
                vmserver.append({
                    "hostname": hostname, "ipaddress": ipaddress, "domain": domain, "os_version": os_version, "os_type": os_type, "manufacturer": manufacturer,
                    "model": model, "sn": sn, "cpu_model": cpu_model, "cpu_socket": cpu_socket, "cpu_cores": cpu_cores, "mem_size": mem_size, "mem_num": mem_num,
                    "disk_size": disk_size,
                })

        return physerver, vmserver
    except Exception as e:
        return e
